package com.zhny.utils;

import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
   图片识别工具类
 */
public class ImgSearchUtils {

    //植物识别
    public static String getPlantName(byte[] imgData){
        return getImgResult("https://aip.baidubce.com/rest/2.0/image-classify/v1/plant",imgData);
    }

    //动物识别
    public static String getAnimalName(byte[] imgData){
        return getImgResult("https://aip.baidubce.com/rest/2.0/image-classify/v1/animal", imgData);
    }

    private static String getImgResult(String url,byte[] imgData){
        try {
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = AuthService.getAuth();//"[调用鉴权接口获取的token]"

            String result = HttpUtil.post(url, accessToken, param);

            System.out.println(result);

            Map map = GsonUtils.fromJson(result, Map.class);
            List<Map<String,String>> nameResult = (List<Map<String, String>>) map.get("result");
            String name = nameResult.get(0).get("name");

            return name;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
